<template>
  <basic-container>
    <avue-crud :option="option" :table-loading="loading" :data="data" :page.sync="page" :permission="permissionList"
      :before-open="beforeOpen" v-model="form" ref="crud" @row-update="rowUpdate" @row-save="rowSave" @row-del="rowDel"
      @search-change="searchChange" @search-reset="searchReset" @selection-change="selectionChange"
      @current-change="currentChange" @size-change="sizeChange" @refresh-change="refreshChange" @on-load="onLoad">
      <!-- 自定义操作列 -->
      <template #menu="{ row, index, size }">
        <el-tooltip class="item" effect="dark" content="审核" placement="top" v-if="row.auth_status == 0">
          <el-button type="primary" :size="'mini'" icon="el-icon-s-check" @click="handleAudit(row, index)" style="width: 23px;
        height: 22px; padding: 0;"></el-button>
        </el-tooltip>

        <el-button type="danger" :size="'mini'" icon="el-icon-delete" @click="rowDel(row, index)" style="width: 23px;
        height: 22px; padding: 0;"></el-button>
      </template>
      <!-- 单元格 -->


      <template slot-scope="{ row }" slot="status">
        <el-switch v-model="row.status" :active-value="0" :inactive-value="1" active-color="#409EFF"
          inactive-color="#d2d6de" active-text="正常" inactive-text="禁用" @change="changeState(row)">
        </el-switch>
      </template>
      <!-- <template slot-scope="{ row }" slot="status">
        <p v-if="row.status == 0" class="normal">正常</p>
        <p v-else-if="row.status == 1" class="un-normal">禁用</p>
      </template> -->
    </avue-crud>
    <!-- 审核弹窗 -->
    <el-dialog :visible.sync="isShowAuditModal" append-to-body destroy-on-close title="审核" width="40%">
      <el-form ref="auditForm" :rules="auditRules" :model="auditForm">
        <el-form-item label="审核结果：" prop="auth_status">
          <el-radio-group v-model="auditForm.auth_status" @change="changeAuthStatus">
            <el-radio :label="3">审核通过</el-radio>
            <el-radio :label="4">审核拒绝 </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核意见：" prop="refuse_reason">
          <el-input type="textarea" v-model="auditForm.refuse_reason"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isShowAuditModal = false"> 取消 </el-button>
        <el-button type="primary" @click="submitAudit()"> 确认 </el-button>
      </div>
    </el-dialog>
  </basic-container>
</template>

<script>
import { getAllBusinessCategory, getShopList, authShopItem, delShopItem, setIsVipShopItem, setShopItemStatus } from "./api/shop";
import { mapGetters } from "vuex";

export default {
  data() {
    return {
      isShowAuditModal: false,
      auditForm: {
        auth_status: 3,
        refuse_reason: '',
      },
      auditRules: {
        auth_status: [
          {
            required: true,
            message: "请选择审核结果",
            trigger: "change",
          },
        ],
        refuse_reason: []
      },
      allBusinessCategoryData: [],
      form: {},
      query: {},
      loading: true,
      page: {
        currentPage: 1,
        pageSize: 10,
        total: 0,
      },
      selectionList: [],
      option: {
        menuType: 'button',
        height: "auto",
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: false,
        index: true,
        indexLabel: '序号',
        searchBtnText: '提交',
        searchBtnIcon: '提交',
        emptyBtnText: '重置',
        emptyBtnIcon: '重置',
        viewBtn: false,
        addBtn: false,
        addBtnText: '添加',
        addBtnIcon: 'el-icon-plus',
        editBtn: false,
        editBtnText: '',
        selection: false,
        dialogClickModal: false,
        delBtn: false,
        delBtnText: '',
        labelWidth: 110,
        searchLabelWidth: 90,
        column: [
          {
            label: "店铺类型",
            prop: "type",
            search: true,
            type: 'select',
            dicData: [{
              label: '普通',
              value: 1
            }, {
              label: '会员',
              value: 2
            }, {
              label: '品牌',
              value: 3
            }, {
              label: '异业联盟',
              value: 4
            }]
          },
          {
            label: "店铺名称",
            prop: "name",
            search: true,
            rules: [{
              required: true,
              message: "请输入店铺名称",
              trigger: "blur"
            }],
          },
          {
            label: "店铺地址",
            prop: "address",
          },
          {
            label: "店铺状态",
            prop: "status",
            search: true,
            type: 'select',
            dicData: [{
              label: '正常',
              value: 0
            }, {
              label: '禁用',
              value: 1
            }],
          },
          {
            label: "审核状态",
            prop: "auth_status",
            search: true,
            type: 'select',
            dicData: [{
              label: '待审核',
              value: 0
            }, {
              label: '审核通过',
              value: 1
            }, {
              label: '审核拒绝',
              value: 2
            }],
          },
          {
            label: "联系人",
            prop: "contact_name",
            search: true,
          },
          {
            label: "联系电话",
            prop: "contact_phone",
            search: true,
          },
          {
            label: "经营类目",
            prop: "business_category_text",
            search: true,
            type: 'select',
            dicData: [],
          },
          {
            label: '营业执照',
            prop: 'license',
            dataType: 'array',
            type: 'upload',
            propsHttp: {
              url: 'file',
              home: $imgBaseUrl
            },
            span: 24,
            listType: 'picture-card',
            accept: [".png", ".jpg", ".jpeg"],
            tip: '上传png、jpg、jpeg的图片',
            action: '/admin/common/upload',
          },
        ],
      },
      data: [],
      currentShopItem: null
    };
  },
  computed: {
    ...mapGetters(["permission"]),

    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.user_add, true),
        viewBtn: this.vaildData(this.permission.user_view, true),
        delBtn: this.vaildData(this.permission.user_delete, true),
        editBtn: this.vaildData(this.permission.user_edit, true),
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
  },
  mounted() {
    // 获取所有经营类目
    getAllBusinessCategory({}).then((res) => {
      const resData = res;
      this.option.column[7].dicData = resData.map(i => {
        return {
          label: i.name,
          value: i.id,
        }
      })
    });
  },
  methods: {
    submitAudit() {
      this.$refs["auditForm"].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({ id: this.currentShopItem.id }, this.auditForm);
          authShopItem(tempData).then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!",
            });
            this.isShowAuditModal = false;
            this.auditForm = {};
          });
        }
      });
    },
    // 审核
    handleAudit(data) {
      this.currentShopItem = data
      this.isShowAuditModal = true
    },
    // 改变状态
    changeState(data) {
      const params = {
        id: data.id,
        status: data.status
      };
      setShopItemStatus(params).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
        },
        (error) => {
          window.console.log(error);
          loading();
        }
      );
    },
    // 是否推荐——————废弃
    // changeIsVip(data) {
    //   const params = {
    //     id: data.id,
    //     is_vip: data.is_vip
    //   };
    //   setIsVipShopItem(params).then(
    //     () => {
    //       this.onLoad(this.page);
    //       this.$message({
    //         type: "success",
    //         message: "操作成功!",
    //       });
    //     },
    //     (error) => {
    //       window.console.log(error);
    //       loading();
    //     }
    //   );
    // },
    rowEdit(row, index) {
      this.$refs.crud.rowEdit(row, index);
    },
    rowDel(row, index) {
      this.$refs.crud.rowDel(row, index);
    },
    rowSave(row, done, loading) {
      const data = row;
      authShopItem(data).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          done();
        },
        (error) => {
          window.console.log(error);
          loading();
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      const data = row;
      console.log(120, row);
      authShopItem(data).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          done();
        },
        (error) => {
          window.console.log(error);
          loading();
        }
      );
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", '提示', {
        cancelButtonText: "取消",
        confirmButtonText: "确定",
        type: "warning",
      })
        .then(() => {
          return delShopItem({ id: row.id });
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
        });
    },

    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      // if (["edit"].includes(type)) {
      //   this.option.column[6].rules = [];
      // } else {
      //   this.option.column[6].rules = [
      //     {
      //       required: true,
      //       message: "请输入密码",
      //       trigger: "blur",
      //     },
      //   ];
      // }
      done();
    },
    changeAuthStatus() {
      this.auditForm.refuse_reason = '';
      if (this.auditForm.auth_status == 4) {
        this.auditRules.refuse_reason = [
          {
            required: true,
            message: "请输入审核意见",
            trigger: "change",
          }
        ]
      } else {
        this.auditRules.refuse_reason = []
      }

    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, search = {}) {
      this.loading = true;
      let param = {
        page: page.currentPage,
        size: page.pageSize,
      }
      getShopList({ ...param, ...search }).then((res) => {
        const resData = res.data;
        this.page.total = resData.total;
        this.data = resData.list;
        this.loading = false;
        this.selectionClear();
      });
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
  },
};
</script>

<style>
.el-switch__label * {
  line-height: 1;
  font-size: 12px;
  display: inline-block;
}

.el-switch__label {
  position: absolute;
  display: none;
  color: #fff !important;
  font-size: 12px !important;
}

/*打开时文字位置设置*/
.el-switch__label--right {
  z-index: 1;
  right: -6px;
}

/*关闭时文字位置设置*/
.el-switch__label--left {
  z-index: 1;
  left: 22px;
}

/*显示文字*/
.el-switch__label.is-active {
  display: block;
}

/*开关宽度*/
.el-switch .el-switch__core,
.el-switch .el-switch__label {
  width: 50px !important;
}
</style>
<style lang="scss" scoped>
// ::v-deep .el-table thead th .cell {
//   border-left: none;
// }

.normal {
  color: #409EFF;
  display: inline-block;
  display: flex;
  align-items: center;

  &::before {
    content: '';
    display: inline-block;
    width: 10px;
    height: 10px;
    border-radius: 10px;
    /**控制形状**/
    background-color: #409EFF;
    /**控制图标颜色**/
    margin-right: 4px
      /**图标与文字距离**/
  }
}

.un-normal {
  color: #d2d6de;
  display: inline-block;

  &::before {
    content: '';
    display: inline-block;
    width: 10px;
    height: 10px;
    border-radius: 10px;
    /**控制形状**/
    background-color: #d2d6de;
    /**控制图标颜色**/
    margin-right: 4px
      /**图标与文字距离**/
  }
}
</style>
